var mongoose = require('mongoose');
var Upload = require("../model/upload");
var multer  = require('multer');

module.exports={    
    //上传新的文件
    create(req,res,next){
        var storage = multer.diskStorage({
            destination: function (req, file, cb) {
              cb(null, './public/uploads/')
            },
            filename: function (req, file, cb) {
              cb(null, file.fieldname + '-' + Date.now()+file.originalname)
            }
        })              
        var upload = multer({ storage: storage }).single('file');

        upload(req, res, function (err) {
            if (err) {
              return
            }
            var fileInfo=req.file;
            
            fileInfo=Object.assign(fileInfo,req.body);
            //console.log(1111,fileInfo)
            const upload=new Upload(fileInfo);
            upload.save().then(data=>{
                //console.log('create')
                res.json(data);
            })           
        })
        
    },
    //修改
    update(req,res,next){
        const id=req.params.id;
        Upload.findByIdAndUpdate(id,{$set:req.body},{new:false}).then((result)=>{
            res.json(result);
        })
    },

    //删除
    delete(req,res,next){
        const id=req.params.id;
        Upload.findByIdAndRemove(id,function(error,result){
            if(error){
                console.log(error)
            }
            else{
                res.json("delete is ok!")
            }          
        })
    },
    //删除多个
    deletemany(req,res,next){
        const id=req.body.id;
        Upload.remove({"_id":{ $in:id}},function(error,result){
            if(error){
                console.log(error)
            }
            else{
                res.json("deletemany is ok!")
            }             
        })
    },
    //搜索
    list(req,res,next){
        var type=req.params.type||0;
        console.log(22,type);
        var page=(req.body.page)?req.body.page:1;
        var limit=(req.body.limit)?req.body.limit:2;
        var queyCondition={};
        if(req.body.name&&req.body.name.trim().length>0){
            name=req.body.name;
            queyCondition={
                "originalname":new RegExp(name,"i")
            }
        }
        queyCondition=Object.assign(queyCondition,{
            type:type
        });
        console.log(queyCondition);
        Upload.paginate(queyCondition,{page:page,limit:limit},(error,results)=>{
            if(error){
                console.log(error)
            }
            else{
                res.json(results);
            }
        })
    },

}